using Unity.VisualScripting;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    [Header("Movement Parameters")]
    public float moveSpeed = 5f;
    public float rotationSpeed = 15f;

    [Header("Combat Parameters")]
    public Transform firePoint;
    public float dashDistance = 3f;
    public float dashCooldown = 2f;
    public float dashDuration = 0.1f;

    private CharacterController characterController;
    private Vector3 moveDirection;
    private Camera mainCamera;
    private bool isDashing;
    private float dashTimer;
    private float cooldownTimer;

    //
    private Weapon currentWeapon;
    private SkillSystem skillSystem;

    private void Awake()
    {
        characterController = GetComponent<CharacterController>();
        mainCamera = Camera.main;
        skillSystem = GetComponent<SkillSystem>();
    }

    private void Start()
    {
        
    }
    private void Update()
    {
        HandleMovement();
        HandleCombatInput();
        HandleDash();
        UpdateTimers();
    }

    private void HandleMovement()
    {
        if (isDashing) return;

        // 
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");

        // 
        Vector3 cameraForward = mainCamera.transform.forward;
        Vector3 cameraRight = mainCamera.transform.right;
        cameraForward.y = 0;
        cameraRight.y = 0;
        cameraForward.Normalize();
        cameraRight.Normalize();

        moveDirection = (cameraForward * vertical + cameraRight * horizontal).normalized;

        // 
        if (moveDirection.magnitude >= 0.1f)
        {
            characterController.Move(moveDirection * moveSpeed * Time.deltaTime);

            // 
            Quaternion targetRotation = Quaternion.LookRotation(moveDirection);
            transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
        }
    }

    private void HandleCombatInput()
    {
        // 
        if (Input.GetMouseButton(0) && currentWeapon != null)
        {
            currentWeapon.Attack();
        }

        // 
        if (Input.GetKeyDown(KeyCode.Q))
        {
            skillSystem.UseSkill(0);
        }

        // 
        if (Input.GetKeyDown(KeyCode.E))
        {
            skillSystem.UseSkill(1);
        }

        // 
        if (Input.GetKeyDown(KeyCode.Alpha1))
        {
            EquipWeapon(0);
        }
        if (Input.GetKeyDown(KeyCode.Alpha2))
        {
            EquipWeapon(1);
        }

        if (Input.GetKeyDown(KeyCode.R))
        {
            if(currentWeapon!= null)
            currentWeapon.StartReload();
        }
    }

    private void HandleDash()
    {
        if (Input.GetKeyDown(KeyCode.Space) && cooldownTimer <= 0 && !isDashing)
        {
            StartDash();
        }

        if (isDashing)
        {
            float distance = dashDistance * (Time.deltaTime / dashDuration);
            characterController.Move(moveDirection.normalized * distance);

            dashTimer += Time.deltaTime;
            if (dashTimer >= dashDuration)
            {
                EndDash();
            }
        }
    }

    private void StartDash()
    {
        isDashing = true;
        //
        GetComponent<PlayerStats>().SetInvulnerable(true);
        //
        EventManager.TriggerEvent(new PlayerDashedEvent());
    }

    private void EndDash()
    {
        isDashing = false;
        dashTimer = 0;
        cooldownTimer = dashCooldown;
        GetComponent<PlayerStats>().SetInvulnerable(false);
    }

    public void EquipWeapon(int index)
    {
        var newWeapon = PlayerInventory.Instance.GetWeapon(index);
        if (newWeapon != null)
        {
            // 销毁上一把武器的实例
            if (currentWeapon != null && currentWeapon.equippedInstance != null)
            {
                Destroy(currentWeapon.equippedInstance);
            }
            
            currentWeapon = newWeapon;
            // 初始化当前装备武器的冷却时间
            currentWeapon.cooldownTimer = 0; // 更新当前装备武器的冷却时间

            if (firePoint != null)
            currentWeapon.Equip(firePoint);

            EventManager.TriggerEvent(new WeaponEquippedEvent(currentWeapon));
        }
    }

    private void UpdateTimers()
    {
        if (cooldownTimer > 0)
        {
            cooldownTimer -= Time.deltaTime;
        }
        
        // 更新当前装备武器的冷却时间
        if (currentWeapon != null && currentWeapon.cooldownTimer > 0)
        {
            currentWeapon.cooldownTimer -= Time.deltaTime;
        }
    }

    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.red;
        if (currentWeapon is MeleeWeapon meleeWeapon)
        {
            // Draw attack range
            Gizmos.DrawWireSphere(firePoint.position, meleeWeapon.attackRange);

            // Draw attack angle
            Vector3 forward = firePoint.forward;
            Vector3 leftBoundary = Quaternion.Euler(0, -meleeWeapon.attackAngle / 2, 0) * forward;
            Vector3 rightBoundary = Quaternion.Euler(0, meleeWeapon.attackAngle / 2, 0) * forward;

            Gizmos.color = Color.yellow;
            Gizmos.DrawRay(firePoint.position, leftBoundary * meleeWeapon.attackRange);
            Gizmos.DrawRay(firePoint.position, rightBoundary * meleeWeapon.attackRange);
        }
    }
}